﻿using Morin.Services;
using Morin.Shared.Models;
using Stylet;
using StyletIoC;
using System.Reflection;

namespace Morin.Wpf.ViewModels.Account;

internal class AccountViewModel(IContainer container, IAppService appService) : Conductor<Screen>
{
    private MenuModel? _menuItem;

    public MenuModel? MenuItem
    {
        get => _menuItem;
        set
        {
            _menuItem = value;
            if (value != null && !string.IsNullOrEmpty(value.ViewModel)) ActivateItem(GetScreen(value.ViewModel));
        }
    }

    public BindableCollection<MenuModel> Menus { get; set; } = [];

    protected override void OnInitialActivate()
    {
        base.OnInitialActivate();
        SetMenusAsync("我的");
    }

    private void SetDefaultMenu()
    {
        MenuItem = Menus.OrderBy(x => x.Sort).First();
    }

    private Task SetMenusAsync(string rootTitle)
    {
        return Task.Run(() =>
        {
            var menus = appService.GetMenus().ToList();
            var rootMenu = menus?.FirstOrDefault(x => x.Title != null && x.Title.Contains(rootTitle));
            if (rootMenu == null) return;

            var nodeMenus = menus?.Where(x => x.Pid == rootMenu.Id);
            if (nodeMenus != null) Menus = [.. nodeMenus];

            SetDefaultMenu();
        });
    }

    private Screen? GetScreen(string viewModel)
    {
        var type = Assembly.GetExecutingAssembly()
            .GetTypes().FirstOrDefault(x => x is { IsClass: true, IsAbstract: false } && x.Name.Equals(viewModel));
        if (type != null) return (Screen)container.Get(type);
        return default;
    }
}